package com.woniu113.junk.gateway.exception;

import cn.hutool.json.JSONUtil;

import com.woniu113.junk.gateway.model.Result;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 全局统一异常处理器
 */
@Component
public class GlobleExceptionHandler implements ErrorWebExceptionHandler {
    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable throwable) {
        throwable.printStackTrace();//打印异常

        //出现异常时的响应,避免代码过多重复,面向异常编程的思想
        Result<?> result = Result.getResult().setMsg("出现异常").setCode(500);//系统级别的异常

        if (throwable instanceof WoniuJunkException){//如果是自定义异常,则要改变result中的消息msg和code
            WoniuJunkException e =(WoniuJunkException) throwable;//先强转成WoniuMovieException才能进行修改
            result.setMsg(e.getMessage());
            result.setCode(e.getCode());
        }
        String json = JSONUtil.parse(result).toString();//json字符串
        exchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_JSON);//响应之前规定上下文类型
        return exchange.getResponse().writeWith(Mono.fromSupplier(()->{
            return exchange.getResponse().bufferFactory().wrap(json.getBytes());
        }));
    }
}
